import { getData, updateData } from '@vimi/utils-api'
import { SERVICE_NAME } from '@/credit/plugins/constant'
import { promise } from '@/common/utils/common'

const state = {
  entrustContract: {},
  entrustContractId: '',
  entrustContractLoading: false,
}

const getters = {
  entrustContract: state => state.entrustContract,
  entrustContractId: state => state.entrustContractId,
  entrustContractLoading: state => state.entrustContractLoading,
}

const actions = {
  async getEntrustContract({ commit }, relatedId) {
    if (!relatedId) {
      return commit('entrustContract', {})
    }
    if (relatedId === state.entrustContractId && state.entrustContractLoading) {
      return
    }
    commit('entrustContractId', relatedId)

    commit('entrustContractLoading', true)
    const [res] = await promise(
      getData(SERVICE_NAME, 'entrust_contract', {
        'customer_related_id.eq': relatedId,
      })
    )
    commit('entrustContractLoading', false)

    commit('entrustContract', (res && res.data && res.data.length && res.data[0]) || {})
  },

  async updateEntrustContract(_, { id, data }) {
    return updateData(SERVICE_NAME, 'entrust_contract', id, data)
  },
}

const mutations = {
  entrustContract: (state, payload) => (state.entrustContract = payload),
  entrustContractId: (state, payload) => (state.entrustContractId = payload),
  entrustContractLoading: (state, payload) => (state.entrustContractLoading = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
